import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useMCPServiceStore = defineStore('mcpService', () => {
  const services = ref([])
  const loading = ref(false)
  const error = ref(null)

  // 获取服务列表
  const getServices = async (params = {}) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.get('/api/mcp/services', { params })
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '获取服务列表失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  // 创建服务
  const createService = async (service) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.post('/api/mcp/services', service)
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '创建服务失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  // 更新服务
  const updateService = async (id, service) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.put(`/api/mcp/services/${id}`, service)
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '更新服务失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  // 删除服务
  const deleteService = async (id) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.delete(`/api/mcp/services/${id}`)
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '删除服务失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  // 测试服务
  const testService = async (id, params) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.post(`/api/mcp/services/${id}/test`, params)
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '测试服务失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  // 获取服务详情
  const getService = async (id) => {
    loading.value = true
    error.value = null
    try {
      const response = await axios.get(`/api/mcp/services/${id}`)
      return response.data
    } catch (err) {
      error.value = err.response?.data?.message || '获取服务详情失败'
      throw error.value
    } finally {
      loading.value = false
    }
  }

  return {
    services,
    loading,
    error,
    getServices,
    createService,
    updateService,
    deleteService,
    testService,
    getService
  }
}) 